import React from 'react';
import { Button, Col, Input, Modal, Popconfirm, Row, Tree } from 'antd';
import { defModalWidth } from '@/defaultSettings';
import styles from './index.less';
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import styled from 'styled-components';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';

const ModalBody = styled.div`
  height: 500px;
  width: 100%;
`;

const { TreeNode } = Tree;

/**
 * 选择行业代码
 */
@connect(({ companyinfo, loading }) => ({
  isLoading: loading.effects['companyinfo/queryBusinessCodes'],
}))
class BusinessCodeSelect extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 一级数据
      l1data: [],
      // 二级数据
      l2data: [],
      // 三级数据
      l3data: [],
      // 被选中的keys
      selectedKeys: [],
    };
  }

  componentDidMount() {
    this.queryBusinessCodes({ pid: 0, level: 1 });
  }

  /**
   * 加载行业代码
   */
  queryBusinessCodes = ({ pid = 0, level = 1, nodename = '' }) => {
    if (this.props.isLoading) {
      return;
    }
    this.execHttp('companyinfo/queryBusinessCodes', { pid })
      .then(value => {
        const { success, list } = value.data;
        if (success) {
          if (level == 1) {
            this.setState({
              l1data: list,
            });
          } else if (level == 2) {
            this.setState({
              l2data: list,
            });
          } else if (level == 3) {
            const children = list.map((each, index) => {
              const { title, value } = each;
              return { title, key: value };
            });
            const node = { title: nodename, key: pid, children };
            this.setState(
              {
                l3data: [node],
              },
              () => {
                console.log(JSON.stringify(list));
              }
            );
          }
        }
      })
      .catch(reason => {});
  };

  render() {
    const { visible, onCancel } = this.props;
    const { l1data, l2data, l3data } = this.state;
    return (
      <Modal
        visible={visible}
        title="选择行业代码"
        width={defModalWidth}
        // onOk={this.handleOk}
        onCancel={onCancel}
        footer={null}
      >
        <ModalBody>
          <Row gutter={16}>
            <Col span={8}>
              <ul className={styles.codelist}>
                {l1data.length > 0
                  ? l1data.map((item, index) => {
                      return (
                        <li
                          className={styles.listItem}
                          key={index}
                          onClick={() => {
                            this.setState({ l2data: [], l3data: [] }, () => {
                              this.queryBusinessCodes({ pid: item.id, level: 2 });
                            });
                          }}
                        >
                          {item.title}
                        </li>
                      );
                    })
                  : null}
              </ul>
            </Col>
            <Col span={8}>
              {l2data.length > 0 ? (
                <ul className={styles.codelist}>
                  {l2data.map((item, index) => {
                    return (
                      <li
                        className={styles.listItem}
                        key={index}
                        onClick={() => {
                          this.setState(
                            {
                              l3data: [],
                            },
                            () => {
                              this.queryBusinessCodes({
                                pid: item.id,
                                level: 3,
                                nodename: item.title,
                              });
                            }
                          );
                        }}
                      >
                        {item.title}
                      </li>
                    );
                  })}
                </ul>
              ) : null}
            </Col>
            <Col span={8}>
              {/*树形节点*/}
              {l3data.length > 0 ? (
                <Tree
                  checkable
                  checkStrictly
                  defaultExpandAll
                  onCheck={this.handleOnSelect}
                  checkedKeys={this.state.selectedKeys}
                >
                  {this.renderTreeNodes(l3data)}
                </Tree>
              ) : null}
            </Col>
          </Row>
        </ModalBody>

        <DivFooter>
          <LFlexHDiv>
            <LFlexHDiv flex={'1'} justifyContent={'center'}>
              <Button
                style={{
                  marginRight: 8,
                }}
                onClick={() => {
                  if (onCancel) {
                    onCancel();
                  }
                }}
              >
                取消
              </Button>

              <Button type="primary" onClick={this.handleSubmit}>
                确定
              </Button>
            </LFlexHDiv>
          </LFlexHDiv>
        </DivFooter>
      </Modal>
    );
  }

  /**
   * 确定按钮被点击
   */
  handleSubmit = () => {
    const { onOkClick } = this.props;
    const { selectedKeys, l3data } = this.state;
    const key = selectedKeys[0];
    const find = l3data.find(each => each.key == key);
    if (find) {
      if (onOkClick) {
        onOkClick(find);
      }
    } else {
      for (let i = 0; i < l3data.length; i++) {
        const { children } = l3data[i];
        const child = children.find(child => child.key == key);
        if (child) {
          if (onOkClick) {
            onOkClick(child);
          }
          break;
        }
      }
    }
  };

  renderTreeNodes = data =>
    data.map((item, index) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });

  handleOnSelect = (checkedKeys, { checked: bool, checkedNodes, node, event, halfCheckedKeys }) => {
    console.log(bool);
    console.log(checkedKeys);
    const { checked } = checkedKeys;
    if (bool) {
      this.setState({
        selectedKeys: [checked[checked.length - 1]],
      });
    } else {
      this.setState({
        selectedKeys: [],
      });
    }
  };
}

export default BusinessCodeSelect;
